<?php

namespace App\Http\Middleware;

use App\Constant;
use App\Models\Agent;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HJSGateway
{
    /** @var int */
    private $startTime;

    /** @var Request */
    private $request;

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        $this->startTime = Carbon::now()->getTimestampMs();
        $this->request = $request;

        $appId = $request->route('agent_id');
        $method = $request->getMethod();

        $agent = \Cache::remember('agent_app_' . $appId, 60 * 5, function () use ($appId) {
            return Agent::query()->where('app_id', $appId)->first();
        });
        if (!$agent) {
            return $this->failResponse('链接中包含无效的AppId');
        }
        $params = 'GET' === $method ? $request->query() : $request->all();
        //TODO: 检查参数签名

        $request->merge([
            'agent_id' => $agent->id,
        ]);
        $resp = $next($request);
        $this->accessLog();

        return $resp;
    }

    private function failResponse($msg)
    {
        $resp = new JsonResponse();
        $this->accessLog();

        return $resp->setData([
            'Success' => false,
            'Code' => 1001,
            'Description' => $msg,
        ]);
    }

    private function accessLog()
    {
        $request = $this->request;
        $cost = Carbon::now()->getTimestampMs() - $this->startTime;
        \Log::channel(Constant::LOG_CHANNEL_HJS)->info(
            sprintf('[IN] %s:%s, COST: %sms', $request->getMethod(), $request->url(), $cost),
            [
                'content-type' => $request->header('Content-Type'),
                'query' => $request->query(),
                'post' => $request->all(),
            ]
        );
    }
}
